package com.example.yupao.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yupao.constant.RedisConstant;
import com.example.yupao.model.domain.User;
import com.example.yupao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author hhf
 * @Date 2024/9/15
 * @Description
 */
@Slf4j
@Component
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    //这里我们暂不缓存所有用户的推荐列表,只为某些高活跃度用户进行缓存预热
    List<Long> activeUserIdList = Arrays.asList(1L, 3L, 7L);


    /**
     * 每天 00:00:00 进行更新活跃用户的推荐列表(前10个)
     */
//    @Scheduled(cron = "0 0 0 * * ? ")
    @Scheduled(cron = "0 28 22 * * ? ")
    public void doCacheRecommendUser() {

        RLock lock = redissonClient.getLock(RedisConstant.RECOMMEND_USER_LOCK);
        try {
            if (lock.tryLock(0, 30000, TimeUnit.MILLISECONDS)) {
                log.info(String.format("%s 获取锁成功", Thread.currentThread().getName()));
                //1.判断活跃用户列表是否有值
                if (activeUserIdList.isEmpty()) {
                    return;
                }
                activeUserIdList.stream().forEach(userId -> {
                    //2.条件查询用户列表
                    Page<User> page = userService.page(Page.of(0, 10));
                    //3.添加到缓存
                    try {
                        redisTemplate.opsForValue().set(RedisConstant.RECOMMEND_USER + userId, page, 25, TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.error("定时任务失败:每天 00:00:00 进行更新活跃用户的推荐列表(前10个)", e);
                    }
                });
            }

        } catch (InterruptedException e) {
            log.error("获取锁成功,但在运行业务逻辑时发生错误", e);
            throw new RuntimeException(e);
        } finally {
            //只有自己上的锁才能解锁
            if (lock.isHeldByCurrentThread()) {
                log.info(String.format("%s 释放锁成功", Thread.currentThread().getName()));
                lock.unlock();
            }
        }


    }

}
